<template>
  <d2-container>
    <el-main>
      <h3>班级名称：</h3>
      <el-input placeholder="请输入班级名称" v-model="name" :disabled="disabled" prop='name' ></el-input>
      <el-row>
        <el-col :span="6">
          <h3>所属校区：</h3>
          <el-select
            v-model="school"
            filterable
            placeholder="可输入名称搜索"
            @change="schoolSelected"
            :disabled="disabled" prop='school'
          >
            <el-option
              v-for="item in schoolList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <h3>教务老师：</h3>
          <el-select v-model="registrar" filterable placeholder="可输入名称搜索(可不填)" :disabled="disabled">
            <el-option
              v-for="item in staffList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <h3>授课教师：</h3>
          <el-select v-model="teacher" filterable placeholder="可输入名称搜索(可不填)" :disabled="disabled" @change="teacherChange">
            <el-option
              v-for="item in staffList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
              
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <h3>开设课程：</h3>
          <el-select v-model="course" filterable placeholder="可输入名称搜索" :disabled="disabled" prop='course'>
            <el-option
              v-for="item in courseList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
<!--       <h3>授课老师单节课上课奖金：</h3>
          <el-input placeholder="请输入奖金（元）" v-model="teacherBonus" :disabled="((teacher == undefined) || disabled)" style="width: 150px"></el-input>元 -->

      <h3>班级状态：</h3>
      <el-radio-group v-model="classStatus" :disabled="disabled">
        <el-radio :label="-1">待进行</el-radio>
        <el-radio :label="0">进行中</el-radio>
        <el-radio :label="1">已结束</el-radio>
      </el-radio-group>
      <el-row :gutter="20">
        <el-col :span="6">
          <div>
            <h3>开始日期：</h3>
            <el-date-picker
              v-model="startDate"
              type="date"
              placeholder="选择开始日期"
              :disabled="disabled"
            ></el-date-picker>
          </div>
        </el-col>
        <el-col :span="6">
          <div>
            <h3>结束日期：</h3>
            <el-date-picker v-model="endDate" type="date" placeholder="选择结束日期" :disabled="disabled"></el-date-picker>
          </div>
        </el-col>
      </el-row>
      <div style="margin:20px 0;">
        <el-radio-group v-model="weekRadio">
          <el-radio-button label="0">周日</el-radio-button>
          <el-radio-button label="1">周一</el-radio-button>
          <el-radio-button label="2">周二</el-radio-button>
          <el-radio-button label="3">周三</el-radio-button>
          <el-radio-button label="4">周四</el-radio-button>
          <el-radio-button label="5">周五</el-radio-button>
          <el-radio-button label="6">周六</el-radio-button>
        </el-radio-group>
      </div>
      <div v-for="(item, index) in classTime" v-show="index == weekRadio">
        <el-button @click="addClass(index)">增加一节课</el-button>
        <div v-for="(hoursItem, hoursIndex) in item.hours">
          <el-row :gutter="20">
            <el-col :span="6">
              <h3>开始时间：</h3>
              <el-select v-model="hoursItem.start" placeholder="请选择(可不填)" :disabled="disabled" @change="selectChange(index,hoursIndex)">
                <el-option
                  v-for="item in times"
                  :key="item.index"
                  :label="item.time"
                  :value="item.index"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <h3>结束时间：</h3>
              <el-select v-model="hoursItem.end" placeholder="请选择(可不填)" :disabled="disabled" @change="selectChange(index,hoursIndex)">
                <el-option
                  v-for="item in times"
                  :key="item.index"
                  :label="item.time"
                  :value="item.index"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <h3>删除：</h3>
              <el-button type="danger" round icon="el-icon-delete" size="small" @click="deleteClass(index,hoursIndex)">
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
      <el-row>
        <!-- <el-col :span="6">
          <h3>上课周期：</h3>
          <el-select v-model="recurrence" multiple placeholder="请选择" :disabled="disabled">
            <el-option
              v-for="item in week"
              :key="item.index"
              :label="item.week"
              :value="item.index"
            ></el-option>
          </el-select>
        </el-col>-->
        <el-col :span="6">
          <h3>所在教室：</h3>
          <el-select v-model="classroom" placeholder="请选择(可不填)" :disabled="disabled">
            <el-option
              v-for="item in classroomList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <h3>班级人数限制：</h3>
      <el-input placeholder="请输入班级人数限制" v-model="studentLimit" type="number" :disabled="disabled" prop='studentLimit'></el-input>
      <h3>班级信息</h3>
      <el-input
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 4}"
        placeholder="请输入内容"
        v-model="classTextarea"
        :disabled="disabled"
      ></el-input>
    </el-main>
    <el-footer>
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="edit" v-show="editShow">修改</el-button>
    </el-footer>
  </d2-container>
</template>

<script>
// import { request } from "http";
import request from "@/plugin/axios";
import { mapState } from "vuex";
export default {
  data() {
    return {
      times: [
        // { time: "00:00", index: 0 },
        // { time: "00:30", index: 1 },
        // { time: "01:00", index: 2 },
        // { time: "01:30", index: 3 },
        // { time: "02:00", index: 4 },
        // { time: "02:30", index: 5 },
        // { time: "03:00", index: 6 },
        // { time: "03:30", index: 7 },
        // { time: "04:00", index: 8 },
        // { time: "04:30", index: 9 },
        // { time: "05:00", index: 10 },
        // { time: "05:30", index: 11 },
        // { time: "06:00", index: 12 },
        // { time: "06:30", index: 13 },
        // { time: "07:00", index: 14 },
        // { time: "07:30", index: 15 },
        { time: "08:00", index: 16 },
        { time: "08:30", index: 17 },
        { time: "09:00", index: 18 },
        { time: "09:30", index: 19 },
        { time: "10:00", index: 20 },
        { time: "10:30", index: 21 },
        { time: "11:00", index: 22 },
        { time: "11:30", index: 23 },
        { time: "12:00", index: 24 },
        { time: "12:30", index: 25 },
        { time: "13:00", index: 26 },
        { time: "13:30", index: 27 },
        { time: "14:00", index: 28 },
        { time: "14:30", index: 29 },
        { time: "15:00", index: 30 },
        { time: "15:30", index: 31 },
        { time: "16:00", index: 32 },
        { time: "16:30", index: 33 },
        { time: "17:00", index: 34 },
        { time: "17:30", index: 35 },
        { time: "18:00", index: 36 },
        { time: "18:30", index: 37 },
        { time: "19:00", index: 38 },
        { time: "19:30", index: 39 },
        { time: "20:00", index: 40 },
        // { time: "20:30", index: 41 },
        // { time: "21:00", index: 42 },
        // { time: "21:30", index: 43 },
        // { time: "22:00", index: 44 },
        // { time: "22:30", index: 45 },
        // { time: "23:00", index: 46 },
        // { time: "23:30", index: 47 }
      ],
      //   week: [
      //     { week: "周日", index: 0 },
      //     { week: "周一", index: 1 },
      //     { week: "周二", index: 2 },
      //     { week: "周三", index: 3 },
      //     { week: "周四", index: 4 },
      //     { week: "周五", index: 5 },
      //     { week: "周六", index: 6 }
      //   ],
      editShow: false,
      disabled: false,
      schoolList: [],
      staffList: [],
      courseList: [],
      classroom: undefined,
      classroomList: [],
      teacherBonus : 0,
      // departmentList: [],
      // department: undefined,
      id: undefined,
      name: undefined,
      school: undefined,
      registrar: undefined,
      teacher: undefined,
      course: undefined,
      classStatus: undefined,
      startDate: undefined,
      endDate: undefined,
      studentLimit: undefined,
      classTextarea: undefined,
      weekRadio: 0,
      classTime: [
        { day: 0, hours: [{ start: undefined, end: undefined }] },
        { day: 1, hours: [{ start: undefined, end: undefined }] },
        { day: 2, hours: [{ start: undefined, end: undefined }] },
        { day: 3, hours: [{ start: undefined, end: undefined }] },
        { day: 4, hours: [{ start: undefined, end: undefined }] },
        { day: 5, hours: [{ start: undefined, end: undefined }] },
        { day: 6, hours: [{ start: undefined, end: undefined }] }
      ],
                  formRules: {
                    studentLimit: [
                        {required: true, message: '限制人数必填', trigger: 'blur'},
                        {min: 0,  message: '请填正数', trigger: 'change'}
                    ],
                    school: [
                        {required: true, message: '学校必填', trigger: 'blur'},
                    ],
                    name: [
                        {required: true, message: '班级名必填', trigger: 'blur'},
                    ],
                    course :  [
                        {required: true, message: '课程', trigger: 'blur'},
                    ],
                },
    };
  },
  computed:{
    ...mapState('d2admin/user',['info'])
  },

  methods: {
    async submit() {
      var data = {};
      var url = "/class/addClass";
      if (this.id != undefined) {
        data.class = this.id;
        url = "/class/updateClass";
      }
      if (this.teacher == undefined){
        data.teacherBonus = null
      }
      else{
        data.teacherBonus = this.teacherBonus
      }
      // if (new Date(this.startDate) > new Date(this.endDate)){
      //   this.$alert('','开始日期必须小于结束日期')
      //   return false
      // }
      (data.registrar = this.registrar == undefined ? null : this.registrar),
        (data.teacher = this.teacher == undefined ? null : this.teacher),
        (data.classroom = this.classroom == undefined ? null : this.classroom),
        (data.name = this.name),
        (data.school = this.school),
        (data.course = this.course),
        // (data.teacherCourse = [{teacher:[this.teacher],course:[this.course]}])
        (data.status = this.classStatus),
        (data.startDate = this.startDate),
        (data.endDate = this.endDate);
      for (let i = 0; i < this.classTime.length; i++) {
        let tempHours = []
        for(let j=0;j<this.classTime[i].hours.length;j++){
          if((this.classTime[i].hours[j].start != undefined) && (this.classTime[i].hours[j].end != undefined)){
            if (this.classTime[i].hours[j].start > this.classTime[i].hours[j].end){
              this.$alert('','上课开始时间必须小于结束时间')
              return false
            }
            tempHours.push(this.classTime[i].hours[j])
          }
        }
        this.classTime[i].hours = tempHours
      }
      (data.classTime = this.classTime),
        (data.studentLimit = this.studentLimit),
        // (data.department = this.department),
        (data.info = this.classTextarea);
      request({
        url: url,
        method: "post",
        data
      }).then(res => {
        if (res.code == 200) {
          this.id = res.data._id
          this.refresh = true
          this.registar = undefined 
                  this.teacher = undefined
                  this.classroom = undefined
                  this.name = undefined
                  // this.school = undefined
                  this.course = undefined
                  this.status = undefined
                  this.startDate = undefined
                  this.endDate = undefined
                  this.classTime = undefined
                  this.studentLimit = undefined
                  this.classTextarea = undefined
                  
          this.$router.push({path:"/class-list"})
          // this.$router.push({path:"/class-detail?class_id=" + this.id + "&tab=studentlist"})
          this.$alert("", "提交成功", {
            confirmButtonText: "确定"
          });
        }
        // 返回数据
      });
    },
    edit() {
      this.disabled = false;
    },
    addClass(e) {
      this.classTime[e].hours.push({ start: undefined, end: undefined });
    },
    deleteClass(e,i){
      this.classTime[e].hours.splice(i,1);
    },
    selectChange(e,i){
      if(this.classTime[e].hours[i].end-this.classTime[e].hours[i].start <= 0){
          this.$alert("选择的结束时间需要大于开始时间", "确认时间", {
            confirmButtonText: "确定"
          });
          this.classTime[e].hours[i].end =this.classTime[e].hours[i].start+1
      }else if(this.classTime[e].hours[i].end-this.classTime[e].hours[i].start >24){
          this.$alert("选择的时长超过12小时", "时间过长", {
            confirmButtonText: "确定"
          });
          this.classTime[e].hours[i].end =this.classTime[e].hours[i].start+8
      }
      else{
        var jojo = []
        for (var i = 0 ; i <this.classTime[e].hours.length;i++){
          jojo.push(this.classTime[e].hours[i])
        }
        var jojo = jojo.sort(function(a,b){return b.start-a.start})
        var i = 1;
        var message = 0
        var temp = 1
        while (i < jojo.length ){
          var j = 0 
          while (j < i){
            if (jojo[j].start < jojo[i].end){
              temp = j
              message = 1 ;
              i = jojo.length
              j = i

            }
            else{
              j = j +1
            }
          }
          i += 1
        }
        if (message != 0){
          this.$alert("时间段不能重合", "时间重合", {
            confirmButtonText: "确定"
          });
          jojo.splice(temp,1)
          this.classTime[e].hours = jojo
        }
      }

    },
    getSchoolList(page, pageSize) {



      let data = {};
      (data.page = page), (data.pageSize = pageSize);
      request({
        url: "/school/getSchoolList",
        method: "post",
        data
      }).then(res => {
        console.log(res);
        this.schoolList = this.info.school
        // 返回数据
      });


    },
    getStaffList(page, pageSize) {
      let data = {};
      (data.page = page), (data.pageSize = pageSize);
      data.school = this.school
      request({
        url: "/staff/getStaffList",
        method: "post",
        data
      }).then(res => {
        this.staffList = [{_id : undefined,name : '不选'}]
        this.staffList = this.staffList.concat(res.data.staff);
        // 返回数据
      });
    },
    getCourseList(page, pageSize) {
      let data = {};
      (data.page = page), (data.pageSize = pageSize);
      data.school = this.school
      request({
        url: "/course/getCourseList",
        method: "post",
        data
      }).then(res => {
        this.courseList = res.data.course;
        // 返回数据
      });
    },
    getClassroomList(page, pageSize) {
      let data = {};
      (data.page = page), (data.pageSize = pageSize);
      data.school = this.school
      request({
        url: "/classroom/getClassroomList",
        method: "post",
        data
      }).then(res => {
                this.classroomList = [{_id : undefined,name : '不选'}]
        this.classroomList = this.classroomList.concat(res.data.classroom);

        // 返回数据
      });
    },
    // getDepartmentList(page, pageSize) {
    //   var data = {};
    //   (data.page = page),
    //     (data.pageSize = pageSize),
    //     (data.school = this.school);
    //   request({
    //     url: "/department/getDepartmentList",
    //     method: "post",
    //     data
    //   }).then(res => {
    //     this.departmentList = res.data;
    //     // 返回数据
    //   });
    // },
    schoolSelected() {
      // this.getDepartmentList(1, 99999);
    },

    teacherChange(){
      var index = this.staffList.map(function(e){return e._id}).indexOf(this.teacher)
      if (index > -1){
          this.teacherBonus = this.staffList[index].teacherBonus == undefined ? 0 : this.staffList[index].teacherBonus
      }
    },
    getClassOne(id) {
      request({
        url: "/class/getClassOne",
        method: "post",
        data: { id: id }
      })
        .then(res => {
          this.id = res.data._id;
          this.name = res.data.name;
          this.school = res.data.school;
          this.registrar = res.data.registrar;
          this.teacher = res.data.teacher;
          this.course = res.data.course;
          this.startDate = res.data.startDate;
          this.endDate = res.data.endDate;
          res.data.hours.forEach(e => {
            if (e.start == -1) {
              e.start = undefined;
            }
            if (e.end == -1) {
              e.end = undefined;
            }
          });
          this.classTime = req.data.hours;
          this.studentLimit = res.data.studentLimit;
          // this.department= res.data.department
          this.classTextarea = res.data.info;
          this.classStatus = res.data.status;
        })
        .then(res => {
          // this.getDepartmentList(1, 99999);
        });
    }
  },

    beforeRouteLeave(to,from,next){
        if (this.refresh){
          to.meta.refresh = 'a'
          this.refresh = undefined
        }
        if (this.$route.query.id == undefined){
            to.meta.keep = true
            to.meta.registar = this.registrar 
            to.meta.teacher = this.teacher
            to.meta.classroom = this.classroom
            to.meta.name = this.name
            to.meta.school = this.school
            to.meta.course = this.course
            to.meta.status = this.status
            to.meta.startDate = this.startDate
            to.meta.endDate = this.endDate
            to.meta.classTime = this.classTime
            to.meta.studentLimit = this.studentLimit
            to.meta.classTextarea = this.classTextarea

                    
        }

        next()
        },
        beforeRouteEnter(to,from,next){
            if (to.meta.keep){
                to.meta.keep = undefined
                next(v=>{
                  v.registar = this.registrar 
                  v.teacher = this.teacher
                  v.classroom = this.classroom
                  v.name = this.name
                  v.school = this.school
                  v.course = this.course
                  v.status = this.status
                  v.startDate = this.startDate
                  v.endDate = this.endDate
                  v.classTime = this.classTime
                  v.studentLimit = this.studentLimit
                  v.classTextarea = this.classTextarea

                  to.meta.registar = undefined 
                  to.meta.teacher = undefined
                  to.meta.classroom = undefined
                  to.meta.name = undefined
                  to.meta.school = undefined
                  to.meta.course = undefined
                  to.meta.status = undefined
                  to.meta.startDate = undefined
                  to.meta.endDate = undefined
                  to.meta.classTime = undefined
                  to.meta.studentLimit = undefined
                  to.meta.classTextarea = undefined
                })
            }
            else{
                next()
            }

        },


  created() {
    if (this.$route.query.id != undefined) {
      this.editShow = true;
      this.disabled = true;
      this.getClassOne(this.$route.query.id);
    }
    this.school = this.info.school[0]._id
    this.getSchoolList(1, 99999);
    this.getStaffList(1, 99999);
    this.getCourseList(1, 99999);
    this.getClassroomList(1, 99999);
  }
};
</script>
